package Clases;

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatThread extends Thread{
    
    
    Vector<PrintStream> clients;
    Socket s;
    String nick;
    BufferedReader entrada;
    PrintStream salida;
    
    public ChatThread(Socket s,Vector<PrintStream> clients, String nick)
    {
	
	try
	    {
		this.s = s;
		this.clients = clients;
		this.nick=nick;
		InputStream in = s.getInputStream();
		OutputStream out = s.getOutputStream();
		
		entrada = new BufferedReader(new InputStreamReader(in));
		salida = new PrintStream(out);
		clients.add(salida);
	    }catch (Exception e)
		{
		    e.printStackTrace();	
		}
	
    }
    
    public void run()
    {
	boolean bye=false;
	while (!bye){
 
	    try
		{
		    
		    String msg="";
		    //Chaque fois que quelqu'un s'ajoute, on dit a tous les usagers que cette personne 
		    //s'est ajoute
		    aviso("Notre ami(e) " + nick + " est entre(e) dans le chat");
		    
		    while (!(msg= entrada.readLine()).equals("quit"))
			{   
			    aviso(msg);
			    System.out.println(">>"+msg);
			}
		    bye=true;
		    
		    //Si le client envoie "quit", on l'enleve de la liste des clients
		    
		    clients.remove(s);
		    salida.println("quit");
		    salida.close();
		    entrada.close();
		}catch(IOException ex){}
	}
    }
    
    //Methode pour envoyer un message a tous les usagers
    private void aviso(String msg)
    {
	Iterator<PrintStream> it = clients.iterator();
	PrintStream client;
	while (it.hasNext())
	    {
		client = it.next();
		client.println(msg); 
		
	    }	
	
    }
    
}